const request = require('request');
const logger = require('../utils/Logger');
const jsapiTicketDao = require('../daos/JsapiTicketDao');
let jsapiTicket = '';

const queryJsapiTicketFromWechat = (accessToken) => {
    let jsapiTicketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + accessToken + '&type=jsapi';
    request({
        url: jsapiTicketUrl,
        method: 'GET'
    }, async function (err, response, body) {
        body = JSON.parse(body);
        if (err) {
            logger.error(`JsapiTicket 从微信服务器请求失败: `, err);
            return;
        }
        jsapiTicket = body.ticket;
        try {
            await jsapiTicketDao.saveJsapiTicket(body);
            logger.info (`JsapiTicket 已更新进数据库`);
            logger.info(`JsapiTicket ${body.ticket}`);
        } catch (e) {
            logger.error (`JsapiTicket 更新失败`,err);
        }
    })
};

const queryJsapiTicketFromDatabase = async (accessToken) => {

    try {
        let ticketInfo = await jsapiTicketDao.getJsapiTicket();
        if (expired(ticketInfo)) {
            queryJsapiTicketFromWechat(accessToken);
        } else {
            jsapiTicket = ticketInfo[0].ticket;
            logger.info(`jsapiTicket ${jsapiTicket} `);
        }
    } catch (e) {
        logger.error(`JsapiTicket 从数据库获取失败`, e)
    }
};

const expired = (rows) => {
    // return true;

    if (rows.length === 0) {
        //此时数据库还没有存jsapiTicket，所以判断为失效
        return true;
    } else {
        let timeRemaining = rows[0].expires_in - Date.now();
        logger.info(`JsapiTicket 距离失效还有：${timeRemaining}毫秒`);
        //如果数据库存的到期时间距离现在已经少于10分钟，则判断为失效
        return rows[0].expires_in - Date.now() < 600000;
    }
};

const initJsapiTicket = accessToken => {
    queryJsapiTicketFromDatabase(accessToken);
};
module.exports = {
    initJsapiTicket: initJsapiTicket,
    queryJsapiTicketFromWechat: queryJsapiTicketFromWechat,
    getJsapiTicket:() => jsapiTicket,
};

